package com.cheng.controller;

import com.cheng.common.utils.BaseResult;
import com.cheng.dto.device.DeviceDTO;
import com.cheng.feign.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@Slf4j
public class FeignController {

    @Resource
    private DeviceService deviceService;

    @Resource
    private RestTemplate restTemplate;

    private static final String DOMAIN_NAME = "server";

    private static final String REQUEST_PROTOCOL = "http://";

    @GetMapping("/device/item/{id}")
    public BaseResult findDeviceItemById(@PathVariable Long id) {
        log.info("================================{}=======================================", id);
        return deviceService.findItem(id);
    }

    @GetMapping("/device/item")
    public BaseResult findDeviceItemByIdForRestTemplate(@RequestParam Long id, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        return getCall(request, params);
    }


    @PostMapping("/device/post/item")
    public BaseResult postMethod(@RequestBody DeviceDTO deviceDTO, HttpServletRequest request) throws URISyntaxException, IOException {
        return postJSONCall(request);
    }


    private BaseResult getCall(HttpServletRequest request, Map<String, Object> params) {
        StringBuilder builder = getRequestUrl(request);
        if (!CollectionUtils.isEmpty(params)) {
            builder.append("?");
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                builder.append(key).append("=").append(params.get(key)).append("&");
            }
        }
        BaseResult result = restTemplate.getForObject(builder.toString(), BaseResult.class);
        return result;
    }

    private BaseResult postJSONCall(HttpServletRequest request) throws URISyntaxException, IOException {
        StringBuilder builder = getRequestUrl(request);
        URI uri = new URI(builder.toString());
        String content = IOUtils.toString(request.getReader());
        log.info(content);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");
        headers.setAll(map);
        Map req_payload = new HashMap();
        req_payload.putAll(request.getParameterMap());
        HttpEntity entity = new HttpEntity(req_payload, headers);
        return restTemplate.postForObject(uri, entity, BaseResult.class);
    }

    private StringBuilder getRequestUrl(HttpServletRequest request) {
        StringBuilder builder = new StringBuilder();
        builder.append(REQUEST_PROTOCOL).append(request.getHeader(DOMAIN_NAME)).append(request.getRequestURI());
        return builder;
    }
}
